package core

import (
	"context"
	"cron_table_admin/global"
	"cron_table_admin/initialize"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"time"

	"go.uber.org/zap"
)

func RunHttpServer() {

	Router := initialize.Routers()
	address := fmt.Sprintf(":%d", global.SERVER_CONFIG.System.Addr)

	s := &http.Server{}
	s.ReadHeaderTimeout = 10 * time.Millisecond
	s.WriteTimeout = 10 * time.Second
	s.MaxHeaderBytes = 1 << 20
	s.Handler = Router
	s.Addr = address
	// 保证文本顺序输出
	// In order to ensure that the text order output can be deleted
	global.LOGGER.Sugar().Debugf("server run success on %s", address)
	env := global.VIPER_CONFIG.Get("system.env")
	global.LOGGER.Debug("当前运行环境为", zap.Any("env", env))
	go func() {
		if err := s.ListenAndServe(); err != nil {
			global.LOGGER.Sugar().Debugf("Listen: %s", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit

	global.LOGGER.Sugar().Debugf("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		global.OPLOGGER.Error("Server Shutdown:", err)
	}
	global.LOGGER.Sugar().Debugf("Server exiting")
}
